/*
 * http://www.digione.cn
 */
package com.jqd.examples.hibernate.tutorial02;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

/**
 * TODO
 * 
 * @author liaozc@digione.cn
 * @date 2012-8-14
 * @since 1.0
 */
@Entity
@Access(AccessType.PROPERTY)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Customer implements Serializable {

	private static final long serialVersionUID = 7430567042895186894L;

	private Long id;

	private String firstName;

	private String lastName;

	private Set<Order> orders = new HashSet<Order>();

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	@Column(length = 30, nullable = false)
	public String getName() {
		if (StringUtils.isNotEmpty(firstName)
				&& StringUtils.isNotEmpty(lastName))
			return firstName + " & " + lastName;
		else
			return StringUtils.EMPTY;
	}

	public void setName(String name) {
		if (StringUtils.isNotEmpty(name)) {
			String[] s = name.split("&");
			firstName = s[0].trim();
			lastName = s[1].trim();
		}
	}

	@OneToMany(mappedBy = "customer", cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)
	public Set<Order> getOrders() {
		return orders;
	}

	public void setOrders(Set<Order> orders) {
		this.orders = orders;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Customer other = (Customer) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}

}
